package org.KeyCrafter.util;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import static java.nio.charset.StandardCharsets.UTF_8;

public class RewriteUtil {
    private static final byte SIMPLE_STRING = '+';
    private static final byte BULK_STRING = '$';
    private static final byte ERROR = '-';
    private static final byte INTEGER = ':';
    private static final byte ARRAY = '*';
    private static final byte[] CTRL = {'\r', '\n'};

    /* 以 "$<count>\r\n<payload>\r\n" 的形式写入二进制安全字符
     *
     * 例如 $3\r\nSET\r\n
     */
    public static void writeBulkString(OutputStream out, String content) throws IOException {
        byte[] bytes = content.getBytes(UTF_8);
        // 写入长度
        writeBulkCount(out, BULK_STRING, bytes.length);
        // 写入内容
        out.write(bytes);
        out.write(CTRL);
    }

    public static void writeArray(OutputStream out, String[] contents) throws IOException {
        writeArray(out, contents, 0, contents.length);
    }

    public static void writeArray(OutputStream out, String[] contents, int off, int len) throws IOException {
        if (contents == null) {
            throw new NullPointerException();
        } else if ((off < 0) || (off > contents.length) || (len < 0) ||
                ((off + len) > contents.length) || ((off + len) < 0)) {
            throw new IndexOutOfBoundsException();
        } else if (len == 0) {
            return;
        }
        // 写入长度
        writeBulkCount(out, ARRAY, len);
        // 写入内容
        for (int i = 0; i < len; i++) {
            writeBulkString(out, contents[off + i]);
        }
    }

    /*
     * 以带 '\r\n' 后缀的形式写入字符串表示的 count 到 out
     * format: "*<count>\r\n".
     */
    private static void writeBulkCount(OutputStream out, byte prefix, int count) throws IOException {
        out.write(prefix);
        out.write(String
                .valueOf(count)
                .getBytes(UTF_8));
        out.write(CTRL);
    }
}
